const App = getApp();
const AJAX = require("../../../../common/request")
const API = require("../../../../common/api")
const common = require("../../../../common/common")
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		navTop: 0,
		navContentHeight: 0,
		placeholderHeight: 0,
		scrollHeight: 0,
		adHeight: 0,
		UPLOADURL: "",
		REQUESTURL: "",
		options: {},
		Reviewlist: [], //评论
		inputValue: "",
		show: false,
		comment: "",
		columnArticleId: "",
		parentId: "",
		index: 0,
		page: 1,
		id: 0,
		APPLETSTATUS: App.globalData.APPLETSTATUS
	},
	commentInput: function (e) {
		this.setData({
			comment: e.detail.value
		})
	},
	setComment(e) {
		//判断缓存手机号是否存在
		if (!App.globalData.user.wxLoginPhone) {
			wx.showToast({
				title: '尚未登录',
				icon: "none"
			})
			wx.navigateTo({
				url: '/pages/login/index',
			})
			return false;
		}
		console.log(e)
		let columnArticleId = e.currentTarget.dataset.columnarticleid
		let parentId = e.currentTarget.dataset.parentid
		let index = e.currentTarget.dataset.index
		this.setData({
			columnArticleId: columnArticleId,
			parentId: parentId,
			index: index
		})
		this.setData({
			show: true,
		})
	},
	closeComment() {

		this.setData({
			show: false,
		})
	},
	async releaseComment() {
		let index = this.data.index
		console.log(this.data.parentId)
		await AJAX.POST("/system/AppWechat/addbbReview", {
			wechatUserId: App.globalData.user.wechatUserId,
			columnArticleId: this.data.id,
			parentId: this.data.parentId,
			comment: this.data.comment,
		}).then(res => {
			if (this.data.parentId != 'null') {
				if (this.data.Reviewlist[index].childen == null) {
					this.setData({
						[`Reviewlist[${index}].childen`]: [res.data],
						show: false,
					})
				} else {
					this.setData({
						[`Reviewlist[${index}].childen`]: this.data.Reviewlist[index].childen.concat(res.data),
						show: false,
					})
				}


			} else {
				this.setData({
					Reviewlist: this.data.Reviewlist.concat(res.data),
					show: false,
				})
			}
			this.getbColumnArticlelist()
		})
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	async onLoad(options) {
		this.setData({
			navTop: App.globalData.navTop,
			navContentHeight: App.globalData.navContentHeight,
			UPLOADURL: API.UPLOADURL,
			REQUESTURL: API.REQUESTURL,
			id: options.id
		})
		const query = wx.createSelectorQuery();
		query.select('.head').boundingClientRect();
		await query.exec((res) => {
			this.setData({
				placeholderHeight: res[0].height,
				scrollHeight: App.globalData.windowHeight - 10
			})
		});

		this.getbColumnArticlelist()
		this.getbReviewlist(options.id)
	},

	async getbColumnArticlelist() {
		await AJAX.POST(`/system/AppWechat/getbColumnArticlelist`, {
			id: this.data.id,
			wechatUserId: App.globalData.user.wechatUserId,
		}).then((res) => {
			if (res.code == 200 && res.rows.length > 0) {
				let data = res.rows[0];
				data.columnArticleIntroduce = data.columnArticleIntroduce.replace(/<img(.*?)>/gi, '<img style="max-width:100%;height:auto" $1/>')
        		data.columnArticleIntroduce = common.addDomainToImageUrls(data.columnArticleIntroduce, this.data.REQUESTURL)
        		//console.log(data.columnArticleIntroduce)
				this.setData({
					options: data
				})
			}
		})
	},
	//获取一级评论
	getbReviewlist(id) {
		let page = this.data.page
		if (this.data.total > 0 && (page - 1) * 10 > this.data.total) {
			console.log("没数据")
			return false;
		}
		let oldData = this.data.Reviewlist
		AJAX.POST("/system/AppWechat/getbReviewlist?pageSize=10&pageNum=" + page, {
			columnArticleId: this.data.id
		}).then((res) => {
			//oldData = oldData.concat(res.rows)
			res.rows.forEach((item) => {
				console.log(item)
				if (oldData.length == 0) {
					oldData.push(item)
				} else {
					let is = false
					oldData.forEach((item2) => {
						if (item.id == item2.id) {
							is = true
						}
					})
					if (!is) {
						oldData.push(item)
					}
				}
			})


			this.setData({
				Reviewlist: oldData,
				page: page + 1,
				total: res.total
			})
		})
	},
	onReachBottom() {
		this.getbReviewlist()
	},
	goBack() {
		const pages = getCurrentPages();
		//获取不到上级返回首页
		if (pages.length > 1) {
			wx.navigateBack({})
		} else {
			wx.reLaunch({
				url: '/pages/index/index',
			})
		}
	},
	// 点赞
	clickLike(e) {

		let addOrDel = this.data.options.dzNum > 0 ? 2 : 1
		//判断缓存手机号是否存在
		if (!App.globalData.user.wxLoginPhone) {
			wx.showToast({
				title: '尚未登录',
				icon: "none"
			})
			wx.navigateTo({
				url: '/pages/login/index',
			})
			return false;
		}
		// 检查登录状态
		common.checkLogin().then((loginRes) => {
			if (!loginRes) {
				return wx.showToast({
					title: '尚未登录，点赞失败',
					duration: "3000",
					icon: "none"
				})
			}

			AJAX.POST("/system/AppWechat/updateNumber", {
				id: e.currentTarget.dataset.id,
				wechatUserId: App.globalData.user.wechatUserId,
				type: 1, // 1点赞，2转发
				addOrDel: addOrDel
			}).then(res => {
				wx.showToast({
					title: addOrDel == 1 ? '点赞完成' : "取消点赞",
				})
				let likeUmber = 0
				if (addOrDel == 1) {
					likeUmber = this.data.options.likenUmber + 1
				} else {
					likeUmber = this.data.options.likenUmber - 1
					likeUmber = likeUmber > 0 ? likeUmber : 0
				}
				this.setData({
					[`options.dzNum`]: addOrDel == 1 ? 1 : 0,
					[`options.likenUmber`]: likeUmber
				})
			})
		})
	},
	// 收藏
	clickCollect(e) {
		if (this.data.options.scNum > 0) {
			return
		}
		//判断缓存手机号是否存在
		if (!App.globalData.user.wxLoginPhone) {
			wx.showToast({
				title: '尚未登录',
				icon: "none"
			})
			wx.navigateTo({
				url: '/pages/login/index',
			})
			return false;
		}
		// 检查登录状态
		common.checkLogin().then((loginRes) => {
			if (!loginRes) {
				return wx.showToast({
					title: '尚未登录，收藏失败',
					duration: "3000",
					icon: "none"
				})
			}
			AJAX.POST("/system/AppWechat/addbCollect", {
				wechatUserId: App.globalData.user.wechatUserId,
				columnArticleId: e.currentTarget.dataset.id
			}).then(res => {
				wx.showToast({
					title: '文章收藏成功',
				})
				this.setData({
					[`options.scNum`]: 1
				})
			})
		})
	},
	onShareAppMessage(options) {
		// 如果该参数存在，则以 resolve 结果为准，如果三秒内不 resolve，分享会使用上面传入的默认参数
		const promise = new Promise(resolve => {
			// 页面按钮点击分享触发
			if (options.from === "button") {
				let params = options.target.dataset.params
				let sharetype = options.target.dataset.sharetype
				// 分享业务类型
				switch (sharetype) {
					// 指定常见病分享配置 sharetype=article_share
					case "article_share":
						resolve({
							title: params.columnArticleTitle || "分享至好友",
							// shareparams 分享链接，由链接进入小程序页面时需要使用的参数值
							path: `/pages/index/article/detail/index?id=${params.id}`,
							imageUrl: ""
						})
						AJAX.POST("/system/AppWechat/updateNumber", {
							id: params.id,
							wechatUserId: App.globalData.user.wechatUserId,
							type: 2 // 1点赞，2转发
						}).catch(err => {
							console.error("转发次数记录失败", err)
						})
						break;

					default:
						break;
				}

			}
		})

		// 默认分享配置
		return {
			title: App.globalData.onShareAppMessage.title,
			path: App.globalData.onShareAppMessage.path,
			imageUrl: App.globalData.onShareAppMessage.imageUrl,
			promise
		}
	},
	ofStatus(e) {
		let index = e.currentTarget.dataset.index
		this.setData({
			[`Reviewlist[${index}].status`]: false
		})
	},
	//获取二级评论
	setStatus(e) {
		let index = e.currentTarget.dataset.index
		let id = this.data.Reviewlist[index].id
		let page = this.data.Reviewlist[index].page ? this.data.Reviewlist[index].page : 1
		let total = this.data.Reviewlist[index].total ? this.data.Reviewlist[index].total : 0
		if (total > 0 && (page - 1) * 10 > total) {
			console.log("没数据")
			return false;
		}
		let status = true
		this.setData({
			[`Reviewlist[${index}].status`]: status
		})

		let oldData = this.data.Reviewlist[index].childen ? this.data.Reviewlist[index].childen : []

		AJAX.POST("/system/AppWechat/getbReviewlistChilden?pageSize=10&pageNum=" + page, {
			columnArticleId: this.data.options.id,
			parentId: id
		}).then((res) => {

			res.rows.forEach((item) => {
				console.log(item)
				if (oldData.length == 0) {
					oldData.push(item)
				} else {
					let is = false
					oldData.forEach((item2) => {
						if (item.id == item2.id) {
							is = true
						}
					})
					if (!is) {
						oldData.push(item)
					}
				}
			})



			this.setData({
				[`Reviewlist[${index}].childen`]: oldData,
				[`Reviewlist[${index}].page`]: page + 1,
				[`Reviewlist[${index}].total`]: res.total
			})
		})
	},

})